import os
import sys
import time
import threading
import subprocess
import tkinter as tk
from tkinter import ttk, filedialog, messagebox

# 导入ttkbootstrap美化
try:
    import ttkbootstrap as ttk
    from ttkbootstrap.constants import *
    from ttkbootstrap.style import Style
    from ttkbootstrap.icons import Icon
    import base64
    from io import BytesIO
    BOOTSTRAP_AVAILABLE = True
    print("使用 ttkbootstrap 美化界面")
except ImportError:
    BOOTSTRAP_AVAILABLE = False
    print("ttkbootstrap 未安装，使用普通 tkinter 界面")
import numpy as np
import queue
import importlib
import shutil
import psutil
import platform
import datetime
import tkinter.font as tkFont

# 导入配置和工具类
import settings
from settings import *
from utils.logger import logger
from utils.window_utils import WindowUtils, get_optimal_window_size
from utils.help_loader import help_loader
from store import params_store, get_param, set_param, reset_params
from windows.pixel_viewer import open_pixel_viewer
from windows.capture_tool import open_capture_tool
from windows.settings_window import open_settings_window
from windows.system_info_window import open_system_info_window
from utils.icon_utils import get_icon_info, get_icon_error, get_icon_warning


class AutoGUI:
    """AutoGUI主类"""
    
    def __init__(self):
        # 创建主窗口（先创建root，再应用外观设置）
        if BOOTSTRAP_AVAILABLE:
            # 使用 ttkbootstrap 主题
            theme = get_param('appearance_theme', 'cosmo')
            self.style = Style(theme=theme)
            self.root = self.style.master
            self.root.title(WINDOW_TITLE)
        else:
            # 使用普通 tkinter
            self.root = tk.Tk()
            self.root.title(WINDOW_TITLE)
        
        # 现在root已创建，应用外观设置
        self.apply_appearance_settings()
        
        # 设置窗口大小
        if get_param('appearance_window_remember_size', True):
            window_width = get_param('appearance_window_width', 1200)
            window_height = get_param('appearance_window_height', 800)
            self.root.geometry(f"{window_width}x{window_height}")
        else:
            # 根据屏幕尺寸自动设置窗口大小
            window_width, window_height = get_optimal_window_size()
            self.root.geometry(f"{window_width}x{window_height}")
        
        if not BOOTSTRAP_AVAILABLE:
            self.root.configure(bg=WINDOW_BG_COLOR)
        
        # 设置窗口大小限制
        if get_param('appearance_window_resizable', True):
            self.root.minsize(*WINDOW_MIN_SIZE)
            self.root.maxsize(*WINDOW_MAX_SIZE)
        else:
            # 固定窗口大小
            self.root.resizable(False, False)
        
        # 初始化变量
        self.is_running = False
        self.frequency_array = None
        self.current_frequency_index = 0
        
        # 创建日志消息队列（线程安全）
        self.log_queue = queue.Queue()
        
        # 设置窗口居中
        self.center_window()
        
        # 创建界面元素
        self.create_widgets()
        
        # 连接日志系统到GUI
        logger.set_gui_callback(self.queue_log_message)
        
        # 启动日志处理
        self.process_log_queue()
        
        # 测试日志系统
        logger.info("日志系统连接测试")
        
        # 加载并显示参数
        self.load_params_info()
        
        logger.info("AutoGUI初始化完成")
    
    def apply_appearance_settings(self):
        """应用外观设置"""
        try:
            # 更新全局字体大小设置
            font_size = get_param('appearance_font_size', 9)
            global FONT_SIZE_NORMAL, FONT_SIZE_BOLD
            FONT_SIZE_NORMAL = font_size
            FONT_SIZE_BOLD = font_size + 1
            
            # 如果窗口大小设置改变，记录当前窗口大小
            if get_param('appearance_window_remember_size', True):
                # 绑定窗口大小变化事件
                def on_window_configure(event):
                    if event.widget == self.root:
                        width = self.root.winfo_width()
                        height = self.root.winfo_height()
                        set_param('appearance_window_width', width)
                        set_param('appearance_window_height', height)
                
                # 延迟绑定，因为此时root还未创建
                self.root.after(100, lambda: self.root.bind('<Configure>', on_window_configure))
                
        except Exception as e:
            logger.error(f"应用外观设置失败: {e}")
    
    def switch_theme(self, theme_name):
        """动态切换主题"""
        try:
            if BOOTSTRAP_AVAILABLE and hasattr(self, 'style'):
                self.style.theme_use(theme_name)
                set_param('appearance_theme', theme_name)
                logger.info(f"主题已切换为: {theme_name}")
        except Exception as e:
            logger.error(f"切换主题失败: {e}")
    
    def load_params_info(self):
        """加载并显示参数信息"""
        try:
            # 获取频率列表
            frequency_list = get_param('_frequency_list', [])
            
            # 显示频率列表（只显示前10个值）
            if frequency_list:
                freq_display = [int(f) for f in frequency_list[:10]]
                if len(frequency_list) > 10:
                    logger.info(f"频率列表 ({len(frequency_list)} 个值): {freq_display}...")
                else:
                    logger.info(f"频率列表 ({len(frequency_list)} 个值): {freq_display}")
            else:
                logger.info("频率列表: 空（未设置起始/结束频率）")
        except Exception as e:
            logger.error(f"加载参数信息失败: {e}")
    
    def center_window(self):
        """将窗口居中显示"""
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f'{width}x{height}+{x}+{y}')
    
    def create_toolbar(self):
        """创建菜单栏"""
        # 创建菜单栏
        menubar = tk.Menu(self.root)
        self.root.config(menu=menubar)
        
        # 设置菜单栏字体为微软雅黑，确保中文字符对齐
        try:
            # 使用项目中的 msyh.ttf 字体文件
            
            # 构建字体文件路径
            font_path = os.path.join(BASE_DIR, 'fonts', 'msyh.ttf')
            
            if os.path.exists(font_path):
                # 使用字体文件路径创建字体
                try:
                    # 尝试使用字体文件路径
                    custom_font = tkFont.Font(family=font_path, size=9)
                    menubar.configure(font=custom_font)
                except:
                    # 如果直接使用路径失败，尝试系统字体
                    custom_font = tkFont.Font(family='Microsoft YaHei', size=9)
                    menubar.configure(font=custom_font)
            else:
                # 如果字体文件不存在，尝试系统字体
                menubar.configure(font=('Microsoft YaHei', 9))
        except:
            try:
                # 尝试其他常见的中文字体
                menubar.configure(font=('SimHei', 9))
            except:
                try:
                    menubar.configure(font=('SimSun', 9))
                except:
                    pass  # 使用默认字体
        
        # 工具菜单
        tools_menu = tk.Menu(menubar, tearoff=0)
        if BOOTSTRAP_AVAILABLE:
            menubar.add_cascade(label="工具", menu=tools_menu)
        else:
            menubar.add_cascade(label="工具    ", menu=tools_menu)
        tools_menu.add_command(
            label="像素查看器",
            command=self.open_pixel_viewer,
            accelerator="Ctrl+P"
        )
        tools_menu.add_command(
            label="截图工具",
            command=self.open_capture_tool,
            accelerator="Ctrl+S"
        )
        tools_menu.add_separator()
        tools_menu.add_command(
            label="重新加载配置",
            command=self.reload_settings
        )
        tools_menu.add_separator()
        tools_menu.add_command(
            label="系统信息",
            command=self.show_system_info,
            accelerator="Ctrl+I"
        )
        
        # 设置菜单
        view_menu = tk.Menu(menubar, tearoff=0)
        if BOOTSTRAP_AVAILABLE:
            menubar.add_cascade(label="设置", menu=view_menu)
        else:
            menubar.add_cascade(label="设置    ", menu=view_menu)
        view_menu.add_command(
            label="参数设置",
            command=self.open_settings_window,
            accelerator="Ctrl+,"
        )
        view_menu.add_separator()
        view_menu.add_command(
            label="清除缓存",
            command=self.clear_cache,
            accelerator="Ctrl+Shift+C"
        )
        
        # 帮助菜单
        help_menu = tk.Menu(menubar, tearoff=0)
        if BOOTSTRAP_AVAILABLE:
            menubar.add_cascade(label="帮助", menu=help_menu)
        else:
            menubar.add_cascade(label="帮助    ", menu=help_menu)
        
        help_menu.add_command(
            label="关于 AutoGUI",
            command=self.show_about,
            accelerator="F1"
        )
        help_menu.add_separator()
        help_menu.add_command(
            label="使用说明",
            command=self.show_help
        )
        help_menu.add_command(
            label="快捷键说明",
            command=self.show_shortcuts
        )
        
        # 绑定快捷键
        self.root.bind('<Control-p>', lambda e: self.open_pixel_viewer())
        self.root.bind('<Control-s>', lambda e: self.open_capture_tool())
        self.root.bind('<Control-comma>', lambda e: self.open_settings_window())
        self.root.bind('<F1>', lambda e: self.show_about())
        self.root.bind('<F12>', lambda e: self.stop_automation())
    
    def open_pixel_viewer(self):
        """打开像素查看器"""
        try:
            viewer = open_pixel_viewer(self.root)
            logger.info("已打开像素查看器")
        except Exception as e:
            logger.error(f"打开像素查看器失败: {e}")
            messagebox.showerror("错误", f"打开像素查看器失败: {str(e)}")
    
    def open_capture_tool(self):
        """打开截图工具"""
        try:
            tool = open_capture_tool(self.root)
            logger.info("已打开截图工具")
        except Exception as e:
            logger.error(f"打开截图工具失败: {e}")
            messagebox.showerror("错误", f"打开截图工具失败: {str(e)}")
    
    def open_settings_window(self):
        """打开参数设置窗口"""
        try:
            settings_win = open_settings_window(self.root)
            logger.info("已打开参数设置窗口")
            # 窗口关闭后重新加载参数信息
            self.root.after(100, self.load_params_info)
        except Exception as e:
            logger.error(f"打开参数设置窗口失败: {e}")
            messagebox.showerror("错误", f"打开参数设置窗口失败: {str(e)}")
    
    def reload_settings(self):
        """重新加载配置"""
        try:
            importlib.reload(settings)
            
            # 重置参数为默认值
            reset_params()
            
            logger.info("配置已重新加载并重置为默认参数")
            messagebox.showinfo("成功", "配置已重新加载并重置为默认参数")
        except Exception as e:
            logger.error(f"重新加载配置失败: {e}")
            messagebox.showerror("错误", f"重新加载配置失败: {str(e)}")
    
    def clear_cache(self):
        """清除项目缓存文件"""
        try:
            
            # 确认对话框
            result = messagebox.askyesno(
                "确认清除缓存",
                "此操作将删除以下缓存文件：\n\n"
                "• __pycache__ 文件夹（Python缓存）\n"
                "• log 文件夹（日志文件）\n"
                "• captures 文件夹（截图文件）\n"
                "• 其他临时文件\n\n"
                "确定要继续吗？"
            )
            
            if not result:
                return
            
            total_size = 0
            
            # 清除 __pycache__ 文件夹
            pycache_dirs = []
            for root, dirs, files in os.walk(BASE_DIR):
                for dir_name in dirs:
                    if dir_name == '__pycache__':
                        pycache_path = os.path.join(root, dir_name)
                        pycache_dirs.append(pycache_path)
            
            for pycache_dir in pycache_dirs:
                try:
                    # 计算文件夹大小
                    dir_size = sum(
                        os.path.getsize(os.path.join(dirpath, filename))
                        for dirpath, dirnames, filenames in os.walk(pycache_dir)
                        for filename in filenames
                    )
                    total_size += dir_size
                    shutil.rmtree(pycache_dir)
                except Exception as e:
                    logger.warning(f"清除 {pycache_dir} 失败: {e}")
            
            # 清除 log 文件夹
            log_dir = os.path.join(BASE_DIR, 'log')
            if os.path.exists(log_dir):
                try:
                    # 计算文件夹大小
                    dir_size = sum(
                        os.path.getsize(os.path.join(dirpath, filename))
                        for dirpath, dirnames, filenames in os.walk(log_dir)
                        for filename in filenames
                    )
                    total_size += dir_size
                    shutil.rmtree(log_dir)
                except Exception as e:
                    logger.warning(f"清除 log 文件夹失败: {e}")
            
            # 清除 captures 文件夹
            captures_dir = os.path.join(BASE_DIR, 'captures')
            if os.path.exists(captures_dir):
                try:
                    # 计算文件夹大小
                    dir_size = sum(
                        os.path.getsize(os.path.join(dirpath, filename))
                        for dirpath, dirnames, filenames in os.walk(captures_dir)
                        for filename in filenames
                    )
                    total_size += dir_size
                    shutil.rmtree(captures_dir)
                except Exception as e:
                    logger.warning(f"清除 captures 文件夹失败: {e}")
            
            # 清除其他临时文件
            for root, dirs, files in os.walk(BASE_DIR):
                # 跳过 venv 文件夹
                if 'venv' in root:
                    continue
                    
                for filename in files:
                    if filename.endswith(('.tmp', '.temp', '.cache', '.bak')):
                        temp_file = os.path.join(root, filename)
                        try:
                            file_size = os.path.getsize(temp_file)
                            total_size += file_size
                            os.remove(temp_file)
                        except Exception as e:
                            logger.warning(f"删除临时文件 {temp_file} 失败: {e}")
            
            # 格式化文件大小
            if total_size > 1024 * 1024:
                size_str = f"{total_size / (1024 * 1024):.2f} MB"
            elif total_size > 1024:
                size_str = f"{total_size / 1024:.2f} KB"
            else:
                size_str = f"{total_size} 字节"
            
            # 显示结果
            if total_size > 0:
                result_text = f"缓存清除完成！\n\n释放空间：{size_str}"
                logger.info(f"缓存清除完成，释放空间：{size_str}")
                messagebox.showinfo("清除缓存", result_text)
            else:
                messagebox.showinfo("清除缓存", "没有找到需要清除的缓存文件。")
                
        except Exception as e:
            logger.error(f"清除缓存失败: {e}")
            messagebox.showerror("错误", f"清除缓存失败：{str(e)}")
    
    def show_system_info(self):
        """显示系统硬件信息"""
        try:
            window = open_system_info_window(self.root)
            if window:
                logger.info("显示系统信息")
            else:
                logger.error("无法打开系统信息窗口")
        except Exception as e:
            logger.error(f"显示系统信息失败: {e}")
            messagebox.showerror("错误", f"显示系统信息失败：{str(e)}")
    
    def show_help(self):
        """显示使用说明"""
        help_text = help_loader.get_help_text()
        
        # 创建帮助窗口
        if BOOTSTRAP_AVAILABLE:
            help_window = ttk.Toplevel(self.root)
            help_window.title("使用说明")
            help_window.geometry("700x600")
            help_window.resizable(True, True)
            
            # 使窗口居中
            help_window.transient(self.root)
            
            # 创建主框架
            main_frame = ttk.Frame(help_window, padding="10")
            main_frame.pack(fill=tk.BOTH, expand=True)
            
            # 创建标题
            title_label = ttk.Label(
                main_frame,
                text="使用说明",
                font=(FONT_FAMILY, FONT_SIZE_BOLD + 2, "bold"),
                bootstyle=PRIMARY
            )
            title_label.pack(pady=(0, 10))
            
            # 创建文本框框架
            text_frame = ttk.LabelFrame(main_frame, text="帮助内容", padding="10")
            text_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
            
            # 创建滚动条
            scrollbar = ttk.Scrollbar(text_frame)
            scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
            
            # 创建文本框
            text_widget = tk.Text(
                text_frame,
                wrap=tk.WORD,
                font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                yscrollcommand=scrollbar.set,
                bg='white',
                fg='black',
                relief=tk.FLAT,
                borderwidth=0
            )
            text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
            scrollbar.config(command=text_widget.yview)
            
            # 插入文本
            text_widget.insert('1.0', help_text)
            text_widget.config(state=tk.DISABLED)
            
            # 创建按钮框架
            button_frame = ttk.Frame(main_frame)
            button_frame.pack(fill=tk.X)
            
            # 关闭按钮
            close_icon = get_icon_error()
            close_btn = ttk.Button(
                button_frame,
                text="关闭",
                image=close_icon if close_icon else '',
                command=help_window.destroy,
                bootstyle=SECONDARY,
                width=15,
                compound=tk.LEFT if close_icon else tk.NONE
            )
            close_btn.pack(side=tk.RIGHT)
            
        else:
            # 普通tkinter版本
            help_window = tk.Toplevel(self.root)
            help_window.title("使用说明")
            help_window.geometry("600x500")
            help_window.resizable(False, False)
            
            # 使窗口居中
            help_window.transient(self.root)
            
            # 创建文本框和滚动条
            text_frame = tk.Frame(help_window)
            text_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
            
            scrollbar = tk.Scrollbar(text_frame)
            scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
            
            text_widget = tk.Text(
                text_frame,
                wrap=tk.WORD,
                font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                yscrollcommand=scrollbar.set
            )
            text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
            scrollbar.config(command=text_widget.yview)
            
            # 插入文本
            text_widget.insert('1.0', help_text)
            text_widget.config(state=tk.DISABLED)
            
            # 关闭按钮
            close_btn = tk.Button(
                help_window,
                text="关闭",
                command=help_window.destroy,
                font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                bg=COLORS['error'],
                fg='white',
                padx=20,
                pady=5
            )
            close_btn.pack(pady=(0, 10))
    
    def show_shortcuts(self):
        """显示快捷键说明"""
        shortcuts_text = help_loader.get_shortcuts_text()
        
        # 创建快捷键说明窗口
        if BOOTSTRAP_AVAILABLE:
            shortcuts_window = ttk.Toplevel(self.root)
            shortcuts_window.title("快捷键说明")
            shortcuts_window.geometry("600x500")
            shortcuts_window.resizable(True, True)
            
            # 使窗口居中
            shortcuts_window.transient(self.root)
            
            # 创建主框架
            main_frame = ttk.Frame(shortcuts_window, padding="10")
            main_frame.pack(fill=tk.BOTH, expand=True)
            
            # 创建标题
            title_label = ttk.Label(
                main_frame,
                text="快捷键说明",
                font=(FONT_FAMILY, FONT_SIZE_BOLD + 2, "bold"),
                bootstyle=PRIMARY
            )
            title_label.pack(pady=(0, 10))
            
            # 创建文本框框架
            text_frame = ttk.LabelFrame(main_frame, text="快捷键列表", padding="10")
            text_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
            
            # 创建滚动条
            scrollbar = ttk.Scrollbar(text_frame)
            scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
            
            # 创建文本框
            text_widget = tk.Text(
                text_frame,
                wrap=tk.WORD,
                font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                yscrollcommand=scrollbar.set,
                bg='white',
                fg='black',
                relief=tk.FLAT,
                borderwidth=0
            )
            text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
            scrollbar.config(command=text_widget.yview)
            
            # 插入文本
            text_widget.insert('1.0', shortcuts_text)
            text_widget.config(state=tk.DISABLED)
            
            # 创建按钮框架
            button_frame = ttk.Frame(main_frame)
            button_frame.pack(fill=tk.X)
            
            # 关闭按钮
            close_icon = get_icon_error()
            close_btn = ttk.Button(
                button_frame,
                text="关闭",
                image=close_icon if close_icon else '',
                command=shortcuts_window.destroy,
                bootstyle=SECONDARY,
                width=15,
                compound=tk.LEFT if close_icon else tk.NONE
            )
            close_btn.pack(side=tk.RIGHT)
            
        else:
            # 普通tkinter版本
            messagebox.showinfo("快捷键说明", shortcuts_text)
    
    def show_about(self):
        """显示关于信息"""
        about_text = help_loader.get_about_text()
        
        # 创建关于窗口
        if BOOTSTRAP_AVAILABLE:
            about_window = ttk.Toplevel(self.root)
            about_window.title("关于 AutoGUI")
            about_window.geometry("500x400")
            about_window.resizable(False, False)
            
            # 使窗口居中
            about_window.transient(self.root)
            
            # 创建主框架
            main_frame = ttk.Frame(about_window, padding="20")
            main_frame.pack(fill=tk.BOTH, expand=True)
            
            # 创建标题
            title_label = ttk.Label(
                main_frame,
                text="关于 AutoGUI",
                font=(FONT_FAMILY, FONT_SIZE_BOLD + 4, "bold"),
                bootstyle=PRIMARY
            )
            title_label.pack(pady=(0, 20))
            
            # 创建文本框框架
            text_frame = ttk.LabelFrame(main_frame, text="软件信息", padding="15")
            text_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 20))
            
            # 创建文本框
            text_widget = tk.Text(
                text_frame,
                wrap=tk.WORD,
                font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                bg='white',
                fg='black',
                relief=tk.FLAT,
                borderwidth=0,
                height=12
            )
            text_widget.pack(fill=tk.BOTH, expand=True)
            
            # 插入文本
            text_widget.insert('1.0', about_text)
            text_widget.config(state=tk.DISABLED)
            
            # 创建按钮框架
            button_frame = ttk.Frame(main_frame)
            button_frame.pack(fill=tk.X)
            
            # 关闭按钮
            close_icon = get_icon_error()
            close_btn = ttk.Button(
                button_frame,
                text="关闭",
                image=close_icon if close_icon else '',
                command=about_window.destroy,
                bootstyle=SECONDARY,
                width=15,
                compound=tk.LEFT if close_icon else tk.NONE
            )
            close_btn.pack(side=tk.RIGHT)
            
        else:
            # 普通tkinter版本
            messagebox.showinfo("关于 AutoGUI", about_text)
    
    def create_widgets(self):
        """创建界面组件"""
        # 创建工具栏
        self.create_toolbar()
        
        # 创建主框架
        if BOOTSTRAP_AVAILABLE:
            main_frame = ttk.Frame(self.root, padding="20")
        else:
            main_frame = tk.Frame(self.root, bg=WINDOW_BG_COLOR)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 左侧控制面板
        if BOOTSTRAP_AVAILABLE:
            control_frame = ttk.LabelFrame(
                main_frame, 
                text="🎮 控制面板", 
                padding="15",
                bootstyle=INFO
            )
        else:
            control_frame = tk.LabelFrame(
                main_frame, 
                text="控制面板", 
                font=(FONT_FAMILY, FONT_SIZE_BOLD, "bold"),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['text']
            )
        control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
        
        # 控制按钮
        self.create_control_buttons(control_frame)
        
        # 右侧日志区域
        self.create_log_area(main_frame)
    
    def create_control_buttons(self, parent):
        """创建控制按钮"""
        if BOOTSTRAP_AVAILABLE:
            button_frame = ttk.Frame(parent)
        else:
            button_frame = tk.Frame(parent, bg=WINDOW_BG_COLOR)
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        
        if BOOTSTRAP_AVAILABLE:
            # 创建图标（保存为实例属性以防止被垃圾回收）
            self.start_icon = get_icon_info()
            self.stop_icon = get_icon_error()
            self.clear_icon = get_icon_warning()
            
            self.start_btn = ttk.Button(
                button_frame,
                text="开始",
                image=self.start_icon if self.start_icon else '',
                command=self.start_automation,
                bootstyle=SUCCESS,
                width=15,
                compound=tk.LEFT if self.start_icon else tk.NONE
            )
            self.start_btn.pack(fill=tk.X, pady=5)
            
            self.stop_btn = ttk.Button(
                button_frame,
                text="停止",
                image=self.stop_icon if self.stop_icon else '',
                command=self.stop_automation,
                bootstyle=DANGER,
                width=15,
                compound=tk.LEFT if self.stop_icon else tk.NONE
            )
            self.stop_btn.pack(fill=tk.X, pady=5)
            
            self.clear_log_btn = ttk.Button(
                button_frame,
                text="清除日志",
                image=self.clear_icon if self.clear_icon else '',
                command=self.clear_log,
                bootstyle=WARNING,
                width=15,
                compound=tk.LEFT if self.clear_icon else tk.NONE
            )
            self.clear_log_btn.pack(fill=tk.X, pady=5)
            
            self.status_label = ttk.Label(
                button_frame,
                text="就绪",
                bootstyle=SECONDARY
            )
            self.status_label.pack(pady=10)
        else:
            self.start_btn = tk.Button(
                button_frame,
                text="开始",
                font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                bg=COLORS['success'],
                fg=COLORS['white'],
                command=self.start_automation,
                height=2
            )
            self.start_btn.pack(fill=tk.X, pady=2)
            
            self.stop_btn = tk.Button(
                button_frame,
                text="停止",
                font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                bg=COLORS['error'],
                fg=COLORS['white'],
                command=self.stop_automation,
                height=2
            )
            self.stop_btn.pack(fill=tk.X, pady=2)
            
            self.clear_log_btn = tk.Button(
                button_frame,
                text="清除日志",
                font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                bg=COLORS['warning'],
                fg=COLORS['white'],
                command=self.clear_log,
                height=2
            )
            self.clear_log_btn.pack(fill=tk.X, pady=2)
            
            self.status_label = tk.Label(
                button_frame,
                text="就绪",
                font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['text']
            )
            self.status_label.pack(pady=5)
    
    def create_log_area(self, parent):
        """创建日志区域"""
        if BOOTSTRAP_AVAILABLE:
            log_frame = ttk.LabelFrame(
                parent,
                text="📋 日志输出",
                padding="10",
                bootstyle=PRIMARY
            )
        else:
            log_frame = tk.LabelFrame(
                parent,
                text="日志输出",
                font=(FONT_FAMILY, FONT_SIZE_BOLD, "bold"),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['text']
            )
        log_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 日志文本框
        if BOOTSTRAP_AVAILABLE:
            self.log_text = tk.Text(
                log_frame,
                font=('Consolas', 9),
                wrap=tk.WORD,
                state=tk.DISABLED
            )
            
            # 滚动条
            scrollbar = ttk.Scrollbar(
                log_frame, 
                orient=tk.VERTICAL, 
                command=self.log_text.yview,
                bootstyle=SECONDARY
            )
        else:
            self.log_text = tk.Text(
                log_frame,
                font=(FONT_FAMILY, 9),
                bg='white',
                fg='black',
                wrap=tk.WORD,
                state=tk.DISABLED
            )
            
            # 滚动条
            scrollbar = tk.Scrollbar(log_frame, orient=tk.VERTICAL, command=self.log_text.yview)
        
        self.log_text.configure(yscrollcommand=scrollbar.set)
        
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=5)
    
    def generate_frequency_array(self):
        """生成频率数组"""
        try:
            # 获取输入参数
            start_val = float(self.freq_start_var.get())
            end_val = float(self.freq_end_var.get())
            step_val = float(self.freq_step_var.get())
            
            # 验证参数
            if step_val <= 0:
                logger.error("错误: 步长必须大于0")
                return
            
            if start_val > end_val:
                logger.error("错误: 初始值不能大于结束值")
                return
            
            # 生成频率数组
            if start_val == end_val:
                freq_array = np.array([start_val])
                logger.info(f"初始值和结束值相同，生成单值频率数组: [{int(start_val)}]")
            else:
                freq_array = np.arange(start_val, end_val + step_val, step_val)
            
            # 更新显示
            array_length = len(freq_array)
            if array_length == 1:
                self.freq_info_label.config(text=f"频率值: {int(freq_array[0])}, 长度: {array_length}")
            else:
                self.freq_info_label.config(text=f"频率范围: {int(freq_array[0])} - {int(freq_array[-1])}, 长度: {array_length}")
            
            # 保存频率数组
            self.frequency_array = freq_array
            
            # 输出日志
            logger.info(f"生成频率数组: 长度={array_length}")
            if array_length == 1:
                logger.info(f"频率值: {int(freq_array[0])}")
            else:
                logger.info(f"频率范围: {int(freq_array[0])} - {int(freq_array[-1])}, 步长: {int(step_val)}")
                logger.info(f"频率数组: {[int(x) for x in freq_array]}")
                
        except ValueError:
            logger.error("错误: 请输入有效的数字")
        except Exception as e:
            logger.error(f"生成频率数组时出错: {e}")
    
    def start_automation(self):
        """开始SIMION无GUI自动化"""
        try:
            # 检查必要参数
            simion_path = get_param('simion_path')
            iob_path = get_param('iob_path')
            lua_path = get_param('lua_path')
            csv_save_path = get_param('csv_save_path')
            frequency_list = get_param('_frequency_list', [])
            
            if not simion_path:
                messagebox.showerror("错误", "请先设置 SIMION 可执行文件路径")
                return
            
            if not iob_path:
                messagebox.showerror("错误", "请先设置 IOB 文件路径")
                return
            
            if not lua_path:
                messagebox.showerror("错误", "请先设置 Lua 文件路径")
                return
                
            if not csv_save_path:
                messagebox.showerror("错误", "请先设置 CSV 保存文件夹")
                return
                
            if not frequency_list:
                messagebox.showerror("错误", "请先设置频率参数并保存")
                return
            
            # 确认开始
            result = messagebox.askyesno(
                "确认开始",
                f"即将开始 SIMION 无GUI自动化\n\n"
                f"SIMION路径: {simion_path}\n"
                f"IOB文件: {iob_path}\n"
                f"Lua文件: {lua_path}\n"
                f"保存路径: {csv_save_path}\n"
                f"频率数量: {len(frequency_list)} 个\n\n"
                f"预计生成 {len(frequency_list)} 个CSV文件\n"
                f"是否继续？"
            )
            
            if not result:
                return
            
            # 初始化停止标志和运行状态
            self.automation_stopped = False
            self.is_running = True
            if BOOTSTRAP_AVAILABLE:
                self.status_label.config(text="自动化运行中...")
            else:
                self.status_label.config(text="自动化运行中...", fg=COLORS['success'])
            
            # 执行自动化脚本
            self.run_nogui_automation()
            
        except Exception as e:
            logger.error(f"启动自动化失败: {e}")
            messagebox.showerror("错误", f"启动自动化失败: {str(e)}")
    
    def run_nogui_automation(self):
        """运行无GUI自动化脚本"""
        try:
            
            # 获取脚本路径
            script_path = os.path.join(BASE_DIR, 'scripts', 'nogui.py')
            
            if not os.path.exists(script_path):
                messagebox.showerror("错误", f"自动化脚本不存在: {script_path}")
                return
            
            # 在后台线程中运行脚本
            def run_script():
                script_start_time = time.time()  # 记录脚本开始时间
                try:
                    # 设置环境变量确保正确的编码
                    env = os.environ.copy()
                    env['PYTHONIOENCODING'] = 'utf-8'
                    
                    # 使用实时输出模式
                    self.automation_process = subprocess.Popen(
                        [sys.executable, script_path],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        text=True,
                        encoding='utf-8',  # 保持UTF-8，因为脚本输出是UTF-8
                        errors='replace',  # 处理编码错误
                        bufsize=1,
                        universal_newlines=True,
                        env=env  # 传递环境变量
                    )
                    
                    # 实时读取输出
                    while True:
                        try:
                            # 检查是否被停止
                            if hasattr(self, 'automation_stopped') and self.automation_stopped:
                                logger.info("用户请求停止自动化，正在终止脚本...")
                                self.automation_process.terminate()
                                try:
                                    self.automation_process.wait(timeout=5)
                                except subprocess.TimeoutExpired:
                                    logger.info("强制终止脚本进程...")
                                    self.automation_process.kill()
                                logger.info("自动化脚本已停止")
                                return
                            
                            output = self.automation_process.stdout.readline()
                            if output == '' and self.automation_process.poll() is not None:
                                break
                            if output:
                                # 安全地处理输出，移除可能的编码问题字符
                                clean_output = output.strip().replace('\ufffd', '?')
                                
                                if clean_output.strip():
                                    if "包含" in clean_output and "行数据" in clean_output:
                                        continue
                                    logger.info(clean_output)
                        except UnicodeDecodeError:
                            continue
                    
                    # 等待进程完成
                    return_code = self.automation_process.poll()
                    
                    # 计算总运行时间
                    script_end_time = time.time()
                    total_script_time = script_end_time - script_start_time
                    
                    # 格式化时间显示
                    hours = int(total_script_time // 3600)
                    minutes = int((total_script_time % 3600) // 60)
                    seconds = int(total_script_time % 60)
                    
                    if hours > 0:
                        time_str = f"{hours}小时{minutes}分钟{seconds}秒"
                    elif minutes > 0:
                        time_str = f"{minutes}分钟{seconds}秒"
                    else:
                        time_str = f"{seconds}秒"
                    
                    # 重置运行状态
                    self.is_running = False
                    
                    if return_code == 0:
                        if BOOTSTRAP_AVAILABLE:
                            self.status_label.config(text="自动化完成")
                        else:
                            self.status_label.config(text="自动化完成", fg=COLORS['success'])
                        messagebox.showinfo("完成", f"SIMION 无GUI自动化已成功完成！\n\n总运行时间: {time_str}")
                    else:
                        error_msg = f"自动化脚本执行失败，返回码: {return_code}\n运行时间: {time_str}"
                        logger.error(error_msg)
                        if BOOTSTRAP_AVAILABLE:
                            self.status_label.config(text="自动化失败")
                        else:
                            self.status_label.config(text="自动化失败", fg=COLORS['error'])
                        messagebox.showerror("错误", error_msg)
                        
                except Exception as e:
                    # 重置运行状态
                    self.is_running = False
                    if BOOTSTRAP_AVAILABLE:
                        self.status_label.config(text="自动化异常")
                    else:
                        self.status_label.config(text="自动化异常", fg=COLORS['error'])
                    logger.error(f"执行自动化脚本时发生错误: {e}")
                    messagebox.showerror("错误", f"执行自动化脚本时发生错误: {str(e)}")
            
            # 启动后台线程
            thread = threading.Thread(target=run_script, daemon=True)
            thread.start()
            
        except Exception as e:
            logger.error(f"运行自动化脚本失败: {e}")
            messagebox.showerror("错误", f"运行自动化脚本失败: {str(e)}")
    
    def run_automation(self):
        """运行自动化任务 - 已禁用"""
        logger.warning("GUI 自动化功能已被移除")
    
    def run_single_frequency_automation(self, frequency_value):
        """运行单个频率值的完整自动化任务 - 已禁用"""
        logger.warning("GUI 自动化功能已被移除")
        messagebox.showinfo("提示", "GUI 自动化功能已被移除\n\n请使用以下工具：\n• 参数设置（Ctrl+,）\n• 像素查看器（Ctrl+P）\n• 截图工具（Ctrl+S）")
        return False
    
    def click_fly_and_wait_for_excel(self, frequency_value):
        """点击Fly按钮并等待Excel生成 - 已禁用"""
        logger.warning("GUI 自动化功能已被移除")
        return False
    
    def return_to_simion_and_screenshot(self, frequency_value):
        """返回SIMION窗口并截图保存 - 已禁用"""
        logger.warning("GUI 自动化功能已被移除")
        return False
    
    def stop_automation(self):
        """停止自动化操作"""
        if not self.is_running:
            messagebox.showinfo("提示", "自动化未在运行")
            return
        
        # 设置停止标志
        self.automation_stopped = True
        
        # 如果有正在运行的进程，强制终止
        if hasattr(self, 'automation_process') and self.automation_process:
            try:
                logger.info("正在停止自动化脚本...")
                self.automation_process.terminate()
                try:
                    self.automation_process.wait(timeout=3)
                except subprocess.TimeoutExpired:
                    logger.info("强制终止脚本进程...")
                    self.automation_process.kill()
                logger.info("自动化脚本已强制停止")
            except Exception as e:
                logger.error(f"停止脚本时发生错误: {e}")
        
        self.is_running = False
        if BOOTSTRAP_AVAILABLE:
            self.status_label.config(text="自动化已停止")
        else:
            self.status_label.config(text="自动化已停止", fg=COLORS['error'])
        logger.info("自动化已停止")
    
    def queue_log_message(self, message):
        """将日志消息放入队列（线程安全）"""
        try:
            self.log_queue.put(message)
        except Exception as e:
            logger.error(f"日志队列错误: {e}")
    
    def process_log_queue(self):
        """处理日志队列中的消息（在主线程中运行）"""
        try:
            # 处理队列中的所有消息
            while not self.log_queue.empty():
                try:
                    message = self.log_queue.get_nowait()
                    self.log_message(message)
                except queue.Empty:
                    break
        except Exception as e:
            logger.error(f"处理日志队列失败: {e}")
        
        # 100ms后再次检查队列
        self.root.after(100, self.process_log_queue)
    
    def log_message(self, message):
        """在日志区域添加消息（仅在主线程中调用）"""
        try:
            # 如果消息已经包含时间戳，直接使用
            if message.startswith('[') and ']' in message:
                log_entry = f"{message}\n"
            else:
                # 否则添加时间戳
                timestamp = datetime.datetime.now().strftime("%H:%M:%S")
                log_entry = f"[{timestamp}] {message}\n"
            
            # 直接更新GUI
            self.log_text.config(state=tk.NORMAL)
            self.log_text.insert(tk.END, log_entry)
            self.log_text.see(tk.END)
            self.log_text.config(state=tk.DISABLED)
            
        except Exception as e:
            # 如果GUI更新失败，至少输出到控制台
            logger.error(f"GUI日志更新失败: {e}")
            logger.error(f"原始消息: {message}")
    
    def clear_log(self):
        """清空日志"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.delete(1.0, tk.END)
        self.log_text.config(state=tk.DISABLED)
    
    def run(self):
        """运行应用程序"""
        logger.info("启动AutoGUI应用程序")
        self.root.mainloop()

if __name__ == "__main__":
    app = AutoGUI()
    app.run()
